<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库单号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入出库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库类型" prop="dispatchType">
        <el-select v-model="queryParams.dispatchType" placeholder="请选择出库类型" clearable>
          <el-option
            v-for="dict in dict.type.dispatch_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择出库状态" clearable>
          <el-option
            v-for="dict in dict.type.dispatch_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dispatchOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dispatchOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dispatchOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:dispatchOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="出库单号" align="center" prop="no" />
      <el-table-column label="出库类型" align="center" prop="dispatchType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dispatch_type" :value="scope.row.dispatchType"/>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="createOrderUser" />
      <el-table-column label="订单状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span>{{ scope.row.status==0?'待审核':'已审核' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="auditor" />
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联单号" align="center" prop="assactionNo" />
      <el-table-column label="订单信息" align="center" prop="info" />
      <el-table-column label="客户名称" align="center" prop="consumerName" />
      <el-table-column label="客户编码" align="center" prop="consumerCode" />
      <el-table-column label="客户联系电话" align="center" prop="contactPhone" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dispatchOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dispatchOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出库单号" prop="no">
          <el-input v-model="form.no" placeholder="请输入出库单号" />
        </el-form-item>
        <el-form-item label="出库类型" prop="dispatchType">
          <el-select v-model="form.dispatchType" placeholder="请选择出库类型">
            <el-option
              v-for="dict in dict.type.dispatch_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联单号" prop="assactionNo">
          <el-input v-model="form.assactionNo" placeholder="请输入关联单号" />
        </el-form-item>
        <el-form-item label="订单信息" prop="info">
          <el-input v-model="form.info" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="客户名称" prop="consumerName">
          <el-input v-model="form.consumerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户编码" prop="consumerCode">
          <el-input v-model="form.consumerCode" placeholder="请输入客户编码" />
        </el-form-item>
        <el-form-item label="客户联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-divider content-position="center">仓库订单详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="toHandleAddWarehouseOrderInfo">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWarehouseOrderInfo">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="dispatchOrderInfoList" :row-class-name="rowWarehouseOrderInfoIndex" @selection-change="handleWarehouseOrderInfoSelectionChange" ref="warehouseOrderInfo">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="产品名称" prop="productName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productName" placeholder="产品名称" disabled />
            </template>
          </el-table-column>
          <el-table-column label="产品编码" prop="productCode" width="150" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.productCode" placeholder="产品编码" disabled />
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="productCode" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productSpec" placeholder="规格" disabled />
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batch" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batch" placeholder="请输入批次号" />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" placeholder="请输入单价" />
            </template>
          </el-table-column>
          <el-table-column label="产品库存数" prop="num1" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.num1" placeholder="请输入数量" disabled />
            </template>
          </el-table-column>
          <el-table-column label="出库数" prop="num" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.num" :max="scope.row.num1" placeholder="请输入数量" />
            </template>
          </el-table-column>
          <el-table-column label="总价" prop="totalPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.totalPrice"  placeholder="请输入总价" :formatter="countTotalPrice" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="请选择产品" :visible.sync="openWarehouseOrderInfo" width="1000px" append-to-body>
      <el-form :model="queryParamsProduct" ref="queryFormProduct" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="产品代码" prop="code">
          <el-input
            v-model="queryParamsProduct.code"
            placeholder="请输入产品代码"
            clearable
            @keyup.enter.native="handleQueryProduct"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input
            v-model="queryParamsProduct.name"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleQueryProduct"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryProduct">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryProduct">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChangeProduct">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="产品代码" align="center" prop="code" />
        <el-table-column label="产品名称" align="center" prop="name" />
        <el-table-column label="工厂代码" align="center" prop="factoryCode" />
        <el-table-column label="内部代码" align="center" prop="innerCode" />
        <el-table-column label="规格" align="center" prop="spec" />
        <el-table-column label="产品类型" align="center" prop="ptname" />
        <el-table-column label="唯一标识" align="center" prop="unid" />
        <el-table-column label="预警上限" align="center" prop="forewarnUp" />
        <el-table-column label="预警下限" align="center" prop="forewarnDown" />
        <el-table-column label="包装类型" align="center" prop="wrapType" />
        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="重量" align="center" prop="weight" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <el-table-column label="客户ID" align="center" prop="customerId" />
        <el-table-column label="产品信息" align="center" prop="info" />
        <el-table-column label="产品数量" align="center" prop="num" />
        <el-table-column label="仓库ID" align="center" prop="storeId" />
        <el-table-column label="位置ID" align="center" prop="locationId" />
      </el-table>

      <pagination
        v-show="totalProduct>0"
        :total="totalProduct"
        :page.sync="queryParamsProduct.pageNum"
        :limit.sync="queryParamsProduct.pageSize"
        @pagination="getProuctList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAddWarehouseOrderInfo">选 择</el-button>
        <el-button @click="cancelWarehouseOrderInfo">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { listdispatchOrder, gedispatchOrder, deldispatchOrder, adddispatchOrder, updatedispatchOrder } from "@/api/system/dispatchOrder";
import { listProductNum} from "@/api/system/product";
import {allPosition} from "../../../api/system/position";
import {
  addDispatchOrder,
  delDispatchOrder,
  listDispatchOrder,
  updateDispatchOrder
} from "../../../api/system/dispatchOrder";

export default {
  name: "DispatchOrder",
  dicts: ['dispatch_type','dispatch_order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      idsProduct: [],
      // 子表选中数据
      checkedWarehouseOrderInfo: [],
      // 非单个禁用
      single: true,
      singleProduct: true,
      // 非多个禁用
      multiple: true,
      multipleProduct: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalProduct: 0,
      // 仓库订单表格数据
      orderList: [],
      // 仓库订单详情表格数据
      dispatchOrderInfoList: [],
      warehousePositList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openWarehouseOrderInfo: false,
      productList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        warehouseType: null,
        status: null,
      },
      queryParamsProduct: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        code: null,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        no: [
          { required: true, message: "出库单号不能为空", trigger: "blur" }
        ],
        createOrderUser: [
          { required: true, message: "制单人不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch:{
    dispatchOrderInfoList:{
      deep:true,
      handler(newVal,oldVal){
        //重修计算总价
        newVal.forEach(warehouseOrderInfo=>{
          warehouseOrderInfo.totalPrice = warehouseOrderInfo.num*warehouseOrderInfo.price;
        })
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询仓库订单列表 */
    getList() {
      this.loading = true;
      listDispatchOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    countTotalPrice(row, column) {
      return row.num*row.prie;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelWarehouseOrderInfo() {
      this.openWarehouseOrderInfo = false;

    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        no: null,
        dispatchType: null,
        createOrderUser: null,
        status: null,
        auditor: null,
        auditTime: null,
        createTime: null,
        assactionNo: null,
        info: null,
        consumerName: null,
        consumerCode: null,
        contactPhone: null
      };
      this.dispatchOrderInfoList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQueryProduct() {
      this.handleQuery.pageNum = 1;
      this.getListProduct();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQueryProduct() {
      this.resetForm("queryFormProduct");
      this.handleQueryProduct();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 多选框选中数据
    handleSelectionChangeProduct(selection) {
      this.idsProduct = selection.map(item => item.id)
      this.singleProduct = selection.length!==1
      this.multipleProduct = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加仓库订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDispatchOrder(id).then(response => {
        this.form = response.data;
        this.dispatchOrderInfoList = response.data.dispatchOrderInfoList;
        this.open = true;
        this.title = "修改仓库订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.dispatchOrderInfoList = this.dispatchOrderInfoList;
          if (this.form.id != null) {
            updateDispatchOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDispatchOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除仓库出库单号为"' + ids + '"的数据项？').then(function() {
        return delDispatchOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 仓库订单详情序号 */
    rowWarehouseOrderInfoIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 仓库订单详情添加按钮操作 */
    toHandleAddWarehouseOrderInfo() {
      this.openWarehouseOrderInfo = true;
      //查询产品
      this.getProuctList();
      this.getWarehousePositList();
    },
    /** 查询库位信息列表 */
    getWarehousePositList() {
      allPosition().then(response => {
        this.warehousePositList = response;
      });
    },
    /** 查询产品信息列表 */
    getProuctList() {
      this.loading = true;
      listProductNum(this.queryParams).then(response => {
        this.productList = response.rows;
        this.totalProduct = response.totalProduct;
        this.loading = false;
      });
    },
    /** 仓库订单详情添加按钮操作 */
    handleAddWarehouseOrderInfo() {
      ;//选择的所有产品的id
      // 使用filter函数根据IDs获取对象
      const selectProductList =  this.productList.filter(obj => this.idsProduct.includes(obj.id));

      selectProductList.forEach(product=>{
        let obj = {};
        obj.num1= product.num;
        obj.productId = product.id;
        obj.productName = product.name;
        obj.productCode = product.code;
        obj.productSpec = product.spec;
        obj.batch = "";
        obj.price =  product.price;
        obj.num = 1;
        obj.totalPrice = obj.price*obj.num;
        obj.warehousePositionId = null;
        this.dispatchOrderInfoList.push(obj);
      })
      this.openWarehouseOrderInfo = false;
      debugger;
    },
    /** 仓库订单详情删除按钮操作 */
    handleDeleteWarehouseOrderInfo() {
      if (this.checkedWarehouseOrderInfo.length == 0) {
        this.$modal.msgError("请先选择要删除的仓库订单详情数据");
      } else {
        const dispatchOrderInfoList = this.dispatchOrderInfoList;
        const checkedWarehouseOrderInfo = this.checkedWarehouseOrderInfo;
        this.dispatchOrderInfoList = dispatchOrderInfoList.filter(function(item) {
          return checkedWarehouseOrderInfo.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWarehouseOrderInfoSelectionChange(selection) {
      this.checkedWarehouseOrderInfo = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dispatchOrder/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
